<template>
  <el-dialog
    v-model="dialogVisible"
    title="分享"
    width="480px"
    :close-on-click-modal="false"
    class="share-dialog"
    :modal-class="'share-dialog-modal'"
    :lock-scroll="true"
    @close="handleClose"
  >
    <div class="share-dialog-content">
      <!-- 分享内容预览 -->
      <div class="share-preview">
        <div v-if="content.image" class="preview-image">
          <el-image :src="content.image" :alt="content.title" fit="cover" />
        </div>
        <div class="preview-content">
          <h3 class="preview-title">{{ content.title }}</h3>
          <p v-if="content.description" class="preview-description">
            {{ content.description }}
          </p>
          <div class="preview-stats">
            <span class="stats-item">
              <el-icon><View /></el-icon>
              {{ formatNumber(content.views || 0) }}
            </span>
            <span class="stats-item">
              <el-icon><Star /></el-icon>
              {{ formatNumber(content.likes || 0) }}
            </span>
            <span class="stats-item">
              <el-icon><Share /></el-icon>
              {{ formatNumber(content.shares || 0) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 分享方式 -->
      <div class="share-section">
        <div class="section-title">
          <span class="title-text">分享方式</span>
          <span class="title-line"></span>
        </div>
        <div class="share-methods">
          <div
            v-for="method in shareMethods"
            :key="method.type"
            class="method-item"
            :class="{ 'is-disabled': method.disabled }"
            @click="!method.disabled && handleShare(method.type)"
          >
            <div class="method-icon" :class="method.type">
              <el-icon><component :is="method.icon" /></el-icon>
            </div>
            <div class="method-name">{{ method.name }}</div>
            <el-tooltip
              v-if="method.disabled"
              effect="dark"
              :content="method.disabledTip"
              placement="top"
            >
              <div class="method-disabled-mask">
                <el-icon><Warning /></el-icon>
              </div>
            </el-tooltip>
          </div>
        </div>
      </div>

      <!-- 分享链接 -->
      <div class="share-section">
        <div class="section-title">
          <span class="title-text">分享链接</span>
          <span class="title-line"></span>
        </div>
        <div class="share-link">
          <el-input v-model="shareLink" readonly class="link-input">
            <template #append>
              <el-button @click="copyLink">
                <el-icon><CopyDocument /></el-icon>
                复制
              </el-button>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 分享设置 -->
      <div class="share-section">
        <div class="section-title">
          <span class="title-text">分享设置</span>
          <span class="title-line"></span>
        </div>
        <div class="share-settings">
          <el-checkbox v-model="settings.withQrCode"
            >生成分享二维码</el-checkbox
          >
          <el-checkbox v-model="settings.includeImage"
            >包含封面图片</el-checkbox
          >
        </div>
      </div>

      <!-- 二维码显示 -->
      <div v-if="settings.withQrCode" class="share-section qr-section">
        <div class="qr-code">
          <div class="qr-wrapper">
            <img :src="qrCodeUrl" alt="二维码" class="qr-image" />
            <div class="qr-tip">扫描二维码分享</div>
          </div>
          <el-button
            type="primary"
            class="download-btn"
            @click="downloadQrCode"
          >
            <el-icon><Download /></el-icon>
            下载二维码
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import {
  Share,
  ChatDotRound,
  Connection,
  Link,
  View,
  Star,
  CopyDocument,
  Download,
  Warning,
} from "@element-plus/icons-vue";
import QRCode from 'qrcode';

// 检查是否在微信浏览器中
const isWeixinBrowser = () => {
  return /MicroMessenger/i.test(navigator.userAgent);
};

// 检查是否在QQ浏览器中
const isQQBrowser = () => {
  return /QQ/i.test(navigator.userAgent);
};

// 更新分享方式列表
const shareMethods = [
  {
    type: "wechat",
    name: "微信",
    icon: "ChatDotRound",
    disabled: !isWeixinBrowser(),
    disabledTip: "请在微信内打开",
  },
  {
    type: "moments",
    name: "朋友圈",
    icon: "Share",
    disabled: !isWeixinBrowser(),
    disabledTip: "请在微信内打开",
  },
  { type: "weibo", name: "微博", icon: "Connection" },
  { type: "qq", name: "QQ", icon: "ChatDotRound" },
  { type: "qzone", name: "QQ空间", icon: "Share" },
  { type: "link", name: "复制链接", icon: "CopyDocument" },
];

// 初始化SDK - 删除实际API调用，保留界面
onMounted(async () => {
  console.log("社交分享组件加载完成");
  // 生成初始二维码
  if (settings.value.withQrCode) {
    generateQRCode();
  }
});

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  content: {
    type: Object,
    required: true,
    default: () => ({
      title: "",
      description: "",
      image: "",
      url: "",
    }),
  },
});

const emit = defineEmits(["update:modelValue", "share"]);

// 对话框可见性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

// 分享设置
const settings = ref({
  withQrCode: false,
  includeImage: true,
});

// 格式化数字
const formatNumber = (num) => {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + "w";
  }
  return num.toString();
};

// 分享链接
const shareLink = computed(() => {
  return props.content.url || window.location.href;
});

// 二维码URL - 使用前端QRCode库生成
const qrCodeUrl = ref('');

// 使用qrcode库生成二维码
const generateQRCode = async () => {
  try {
    qrCodeUrl.value = await QRCode.toDataURL(shareLink.value, {
      width: 180,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#ffffff'
      }
    });
  } catch (error) {
    console.warn("二维码生成失败", error);
    // 默认空白图片作为备用
    qrCodeUrl.value = '';
  }
};

// 监听withQrCode变化，生成二维码
watch(
  () => settings.value.withQrCode,
  (newVal) => {
    if (newVal) {
      generateQRCode();
    }
  }
);

// 监听shareLink变化，更新二维码
watch(
  shareLink,
  () => {
    if (settings.value.withQrCode) {
      generateQRCode();
    }
  }
);

// 处理分享
const handleShare = async (type) => {
  try {
    const shareData = {
      title: props.content.title,
      desc: props.content.description,
      link: shareLink.value,
      imgUrl: props.content.image,
    };

    switch (type) {
      case "wechat":
        if (isWeixinBrowser()) {
          ElMessage.success("请点击右上角菜单进行分享");
        } else {
          settings.value.withQrCode = true;
          ElMessage.info("请使用微信扫描二维码进行分享");
        }
        break;

      case "moments":
        if (isWeixinBrowser()) {
          ElMessage.success("请点击右上角菜单分享到朋友圈");
        } else {
          settings.value.withQrCode = true;
          ElMessage.info("请使用微信扫描二维码进行分享");
        }
        break;

      case "weibo":
        // 使用微博开放API进行分享
        const weiboData = {
          url: shareLink.value,
          title: `${props.content.title} ${props.content.description}`,
          pic: props.content.image,
          appkey: '', // 删除appkey
        };

        const weiboShareUrl = `http://service.weibo.com/share/share.php?url=${encodeURIComponent(weiboData.url)}&title=${encodeURIComponent(weiboData.title)}&pic=${encodeURIComponent(weiboData.pic)}`;

        // 打开新窗口进行分享
        window.open(
          weiboShareUrl,
          "_blank",
          "width=700,height=680,left=0,top=0,toolbar=no,menubar=no,scrollbars=no,location=yes,resizable=no,status=no",
        );
        
        ElMessage.success("分享成功");
        emit("share", { type, content: props.content });
        break;

      case "qq":
        const qqData = {
          url: shareLink.value,
          title: props.content.title,
          desc: props.content.description,
          pics: props.content.image,
        };

        // 使用QQ分享接口
        const qqShareUrl = `http://connect.qq.com/widget/shareqq/index.html?url=${encodeURIComponent(qqData.url)}&title=${encodeURIComponent(qqData.title)}&summary=${encodeURIComponent(qqData.desc)}&pics=${encodeURIComponent(qqData.pics)}`;

        // 打开新窗口进行分享
        window.open(
          qqShareUrl,
          "_blank",
          "width=700,height=680,left=0,top=0,toolbar=no,menubar=no,scrollbars=no,location=yes,resizable=no,status=no",
        );
        
        ElMessage.success("分享成功");
        emit("share", { type, content: props.content });
        break;

      case "qzone":
        const qzoneData = {
          url: shareLink.value,
          title: props.content.title,
          summary: props.content.description,
          pics: props.content.image,
        };

        // 使用QQ空间分享接口
        const qzoneShareUrl = `https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=${encodeURIComponent(qzoneData.url)}&title=${encodeURIComponent(qzoneData.title)}&summary=${encodeURIComponent(qzoneData.summary)}&pics=${encodeURIComponent(qzoneData.pics)}`;

        // 打开新窗口进行分享
        window.open(
          qzoneShareUrl,
          "_blank",
          "width=700,height=680,left=0,top=0,toolbar=no,menubar=no,scrollbars=no,location=yes,resizable=no,status=no",
        );
        
        ElMessage.success("分享成功");
        emit("share", { type, content: props.content });
        break;

      case "link":
        await copyLink();
        break;
    }
  } catch (error) {
    console.warn("分享操作失败");
  }
};

// 复制链接
const copyLink = async () => {
  try {
    await navigator.clipboard.writeText(shareLink.value);
    ElMessage.success("链接已复制");
  } catch (error) {
    console.warn("复制失败");
    ElMessage.error("复制失败，请手动复制");
  }
};

// 下载二维码
const downloadQrCode = () => {
  const link = document.createElement("a");
  link.href = qrCodeUrl.value;
  link.download = `qrcode-${Date.now()}.png`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  ElMessage.success("二维码已下载");
};

// 关闭对话框
const handleClose = async () => {
  settings.value.withQrCode = false;
};
</script>

<style lang="scss" scoped>
.share-dialog {
  :deep(.el-dialog) {
    margin: 0 !important;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    max-height: 80vh;
    display: flex;
    flex-direction: column;
  }

  :deep(.el-dialog__header) {
    padding-top: 16px;
    margin-right: 0;
    border-bottom: 1px solid var(--el-border-color-lighter);
  }

  :deep(.el-dialog__body) {
    padding: 0;
    flex: 1;
    overflow: hidden;
  }

  :deep(.el-dialog__headerbtn) {
    top: 16px;
  }
}

.share-dialog-content {
  height: calc(80vh - 120px);
  overflow-y: auto;
  overflow-x: hidden;
  padding: 24px;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: var(--el-border-color-darker);
    border-radius: 3px;
  }

  &::-webkit-scrollbar-track {
    background-color: var(--el-border-color-light);
    border-radius: 3px;
  }
}

:deep(.share-dialog-modal) {
  background-color: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(4px);
}

.share-preview {
  @apply mb-6 bg-gray-50 dark:bg-gray-800 rounded-lg overflow-hidden transition-colors;

  .preview-image {
    @apply relative w-full h-48;

    :deep(.el-image) {
      @apply w-full h-full object-cover;
    }

    &::after {
      content: "";
      @apply absolute inset-0 bg-gradient-to-b from-transparent to-black/30;
    }
  }

  .preview-content {
    @apply p-4;

    .preview-title {
      @apply text-lg font-medium text-gray-900 dark:text-white mb-2;
    }

    .preview-description {
      @apply text-sm text-gray-600 dark:text-gray-400 line-clamp-2 mb-3;
    }

    .preview-stats {
      @apply flex items-center gap-4;

      .stats-item {
        @apply flex items-center text-sm text-gray-500 dark:text-gray-400;

        .el-icon {
          @apply mr-1;
        }
      }
    }
  }
}

.share-section {
  @apply mb-6;

  .section-title {
    @apply flex items-center mb-4;

    .title-text {
      @apply text-sm text-gray-500 dark:text-gray-400 mr-3;
    }

    .title-line {
      @apply flex-1 h-px bg-gray-200 dark:bg-gray-700;
    }
  }
}

.share-methods {
  @apply grid grid-cols-3 sm:grid-cols-6 gap-4;

  .method-item {
    @apply relative flex flex-col items-center cursor-pointer transition-transform hover:scale-105;

    &.is-disabled {
      @apply opacity-60 cursor-not-allowed hover:scale-100;
    }

    .method-icon {
      @apply w-12 h-12 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-2 transition-colors;

      .el-icon {
        @apply text-xl;
      }

      &.wechat {
        @apply bg-green-50 dark:bg-green-900/20 text-green-600;
      }

      &.moments {
        @apply bg-green-50 dark:bg-green-900/20 text-green-600;
      }

      &.weibo {
        @apply bg-red-50 dark:bg-red-900/20 text-red-600;
      }

      &.qq {
        @apply bg-blue-50 dark:bg-blue-900/20 text-blue-600;
      }

      &.qzone {
        @apply bg-yellow-50 dark:bg-yellow-900/20 text-yellow-600;
      }

      &.link {
        @apply bg-purple-50 dark:bg-purple-900/20 text-purple-600;
      }
    }

    .method-name {
      @apply text-sm text-gray-600 dark:text-gray-400;
    }

    .method-disabled-mask {
      @apply absolute inset-0 flex items-center justify-center bg-black/5 dark:bg-white/5 rounded-lg;

      .el-icon {
        @apply text-yellow-500;
      }
    }
  }
}

.share-link {
  @apply relative;

  .link-input {
    :deep(.el-input__wrapper) {
      @apply bg-gray-50 dark:bg-gray-800;
    }

    :deep(.el-input-group__append) {
      @apply bg-transparent border-0 px-0;
    }
  }
}

.share-settings {
  @apply flex items-center gap-6;
}

.qr-section {
  @apply flex justify-center;

  .qr-code {
    @apply flex flex-col items-center;

    .qr-wrapper {
      @apply p-4 bg-white dark:bg-gray-800 rounded-lg shadow-sm mb-3;

      .qr-image {
        @apply w-40 h-40;
      }

      .qr-tip {
        @apply mt-2 text-center text-sm text-gray-500 dark:text-gray-400;
      }
    }

    .download-btn {
      @apply flex items-center;

      .el-icon {
        @apply mr-1;
      }
    }
  }
}

// 优化暗色模式
:deep(.dark) {
  .el-dialog {
    @apply bg-gray-900 border-gray-700;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
  }

  .el-dialog__header {
    border-bottom-color: var(--el-border-color-darker);
  }

  .share-dialog-content {
    &::-webkit-scrollbar-thumb {
      background-color: var(--el-border-color-light);
    }

    &::-webkit-scrollbar-track {
      background-color: var(--el-border-color-darker);
    }
  }
}

// 添加响应式调整
@media screen and (max-height: 600px) {
  .share-dialog {
    :deep(.el-dialog) {
      max-height: 95vh;
    }
  }

  .share-dialog-content {
    height: calc(95vh - 120px);
  }
}

// 添加动画效果
.method-item {
  @apply transform transition-all duration-200;

  &:hover:not(.is-disabled) {
    .method-icon {
      @apply shadow-lg;
    }
  }
}
</style>
